package org.huqiwen.blog.logic;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.huqiwen.blog.dao.DataSource;
import org.huqiwen.blog.dao.ExecuteOptionSQL;
import org.huqiwen.blog.data.MessageDataBean;
/**
 * 留言的业务逻辑处理
 * @author Administrator
 *
 */
public class MessageLogicBean {
	private int allRows;
	private int curPage = 1;
	private int allPage;
	private int pageSize = 10;
	public int getAllRows() {
		return allRows;
	}
	public void setAllRows(int allRows) {
		this.allRows = allRows;
	}
	public int getCurPage() {
		return curPage;
	}
	public void setCurPage(int curPage) {
		this.curPage = curPage;
	}
	public int getAllPage() {
		return allPage;
	}
	public void setAllPage(int allPage) {
		this.allPage = allPage;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	/**
	 * 返回留言的列表
	 * @return
	 */
	public List<MessageDataBean> findAll(){
		List<MessageDataBean> list = new ArrayList<MessageDataBean>();
		Statement stmt = null;
		ResultSet rs = null;
		try{
			String sql="select * from message";
			stmt = DataSource.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
			rs = stmt.executeQuery(sql);
			rs.last();
			this.allRows = rs.getRow();
			if (this.allRows%this.pageSize==0) {
				this.allPage = this.allRows/this.pageSize;
			}else {
				this.allPage = this.allRows/this.pageSize + 1;
			}
			
			if (curPage == 1) {
				rs.beforeFirst();
			}else {
				rs.absolute((this.curPage-1)*this.pageSize);
			}
			int i = 0;
			while(rs.next()&&i<this.pageSize){
				MessageDataBean bean = new MessageDataBean();
				bean.setMsgId(rs.getString(1));
				bean.setMsgTitle(rs.getString(2));
				bean.setMsgName(rs.getString(3));
				bean.setMsgContent(rs.getString(4));
				bean.setMsgIp(rs.getString(5));
				bean.setMsgDate(rs.getString(6));
				list.add(bean);
				i++;
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			try {
				if(stmt!=null) stmt.close();
				if(rs!=null)rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}
	/**
	 * 根据传入的参数添加留言
	 * @param title
	 * @param name
	 * @param content
	 * @param messageIP
	 * @return
	 */
	public int addMessage(String title,String name,String content,String messageIP){
		return ExecuteOptionSQL.UpdateSQL("insert into message(msg_title,msg_name,msg_content,msg_ip,msg_date) values ('" +
				title+"','"+name+"','"+content+"','"+messageIP+"',now())");
	}
	/**
	 * 根据传入的参数，留言的id，删除相应的留言信息
	 * @param id
	 * @return
	 */
	public int delMessage(String id){
		return ExecuteOptionSQL.UpdateSQL("delete from message where msg_id = "+id);
	}
}
